/**
 * 生成 link node
 * @param url url
 * @param text text
 */

// 插入文章的自定义菜单
import { IDomEditor, IButtonMenu, SlateNode, SlateElement, SlateEditor, DomEditor } from '@wangeditor/editor';
import { IExtendConfig } from '../../customLink/interface';
import { PENCIL_SVG } from '../../icon-svg';

function getInsertLinkConfig(editor: IDomEditor) {
  const { EXTEND_CONF } = editor.getConfig();
  const { insertLinkConfig } = EXTEND_CONF as IExtendConfig;
  return insertLinkConfig;
}


class EditLinkCardMenu implements IButtonMenu {
  tag: string;
  title: string;
  iconSvg: string;
  selectedLinkNode: SlateNode | null = null;

  constructor() {
    this.title = '修改链接';
    this.iconSvg = PENCIL_SVG;
    this.tag = 'button';
    this.selectedLinkNode = null;
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {
    // TS 语法
    return false;
  }

  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {
    // TS 语法
    return '';
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {
    // TS 语法
    return false;
  }

  // 点击菜单时触发的函数
  exec(editor: IDomEditor, value: string | boolean) {
    if (this.isDisabled(editor)) return;
    console.log('点击了自定义菜单-修改链接');
    const nodeEntries = SlateEditor.nodes(editor, {
      match: (node) => {
        if (SlateElement.isElement(node)) {
          return true;
        }
        return false;
      },
      universal: true,
    });
    for (const nodeEntry of nodeEntries) {
      const [node] = nodeEntry;
      this.selectedLinkNode = node;
    }
    console.log('点击了编辑卡片菜单：', this.selectedLinkNode);
    const target = this.selectedLinkNode?.target;
    const type = this.selectedLinkNode?.type

    const linkText = this.selectedLinkNode?.title;
    const linkAddress = this.selectedLinkNode?.link;
    const articleId = this.selectedLinkNode?.articleId ;

    // 这里需要判断是文章链接还是普通链接
    const articleParam = {
      linkText,
      linkAddress,
      articleId,
      type,
      target,
      linkType:type,
    };
    console.log('修改卡片链接的文章参数', articleParam);
    const { showInsertArticleModal } = getInsertLinkConfig(editor);
    showInsertArticleModal(editor,type,articleParam);
  }
}

export default EditLinkCardMenu;
